package com.executor.gateway.controller;

import com.executor.gateway.core.GlobalExceptionHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 异常处理测试控制器
 * 用于测试全局异常处理器的功能
 * 
 * @author miaoguoxin
 * @date 2024/01/01
 */
@RestController
@RequestMapping("/test/exception")
@Slf4j
public class ExceptionTestController {

    @Autowired
    private GlobalExceptionHandler globalExceptionHandler;

    /**
     * 测试NotFoundException
     */
    @GetMapping("/not-found")
    public ResponseEntity<String> testNotFoundException() {
        throw new NotFoundException("Test route not found");
    }

    /**
     * 测试IllegalArgumentException
     */
    @GetMapping("/bad-request")
    public ResponseEntity<String> testBadRequest(@RequestParam String param) {
        if ("invalid".equals(param)) {
            throw new IllegalArgumentException("Invalid parameter value: " + param);
        }
        return ResponseEntity.ok("Valid parameter");
    }

    /**
     * 测试SecurityException
     */
    @GetMapping("/unauthorized")
    public ResponseEntity<String> testUnauthorized() {
        throw new SecurityException("Access denied for test purposes");
    }

    /**
     * 测试一般异常
     */
    @GetMapping("/internal-error")
    public ResponseEntity<String> testInternalError() {
        throw new RuntimeException("Test internal server error");
    }

    /**
     * 获取异常处理器状态
     */
    @GetMapping("/handler-status")
    public ResponseEntity<Map<String, Object>> getHandlerStatus() {
        Map<String, Object> status = new HashMap<>();
        status.put("enhancedMode", globalExceptionHandler.isEnhancedMode());
        status.put("handlerClass", globalExceptionHandler.getClass().getSimpleName());
        status.put("timestamp", System.currentTimeMillis());
        return ResponseEntity.ok(status);
    }

    /**
     * 切换异常处理模式
     */
    @PostMapping("/toggle-mode")
    public ResponseEntity<Map<String, Object>> toggleMode(@RequestParam boolean enhanced) {
        globalExceptionHandler.setEnhancedMode(enhanced);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("enhancedMode", globalExceptionHandler.isEnhancedMode());
        result.put("message", enhanced ? "Switched to enhanced mode" : "Switched to legacy mode");
        
        log.info("Exception handler mode switched to: {}", enhanced ? "enhanced" : "legacy");
        return ResponseEntity.ok(result);
    }
}